<template>
  <div id="staModelSeDiv">
    <Splitpanes>
      <Pane size="20">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-input style="width: 180px" v-model="searchModelForm.seachValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getStaModelList" @keyup="keyupModelEnter" @search-click="getStaModelList()"></vxe-input>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addStaModelDialog()"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteStaModel"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="modelTable">
          <vxe-table ref="staModelTableRef" class="mytable-scrollbar staModelTableClazz" border="inner" align="center" height="auto" :data="staModelList" :loading="tloading" @current-change="modelRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
            <vxe-column type="checkbox" width="30"></vxe-column>
            <vxe-column field="modelCode" title="模型编号" width="100">
              <template #default="{ row }">
                <el-link type="primary" :underline="false" @click="editStaModelDialog(row)">
                  <span>{{row.modelCode}}</span>
                </el-link>
              </template>
            </vxe-column>
            <vxe-column field="modelName" title="模型名称">
            </vxe-column>
            <vxe-column field="seq" title="顺序" width="50">
            </vxe-column>
          </vxe-table>
        </div>
        <vxe-modal v-model="isModelVisiable" width="25vw" height="35vh" show-footer :mask="false" @close="cancelModelEvent">
          <template #title>
            <span>模型</span>
          </template>
          <template #default>
            <div class="form-panel">
              <vxe-form :data="staModelForm" title-width="80">
                <vxe-form-item title="模型编号" span="24" field="modelCode">
                  <template #default="{ data }">
                    <vxe-input v-model="data.modelCode" placeholder="模型编号"></vxe-input>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="模型名称" span="24" field="modelName">
                  <template #default="{ data }">
                    <vxe-input v-model="data.modelName" placeholder="模型名称"></vxe-input>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="顺序" field="seq" span="24" :item-render="{}" title-overflow="title">
                  <template #default="params">
                    <vxe-input v-model="params.data.seq" type="number" min="0" max="1000" placeholder="顺序"></vxe-input>
                  </template>
                </vxe-form-item>

              </vxe-form>
            </div>
          </template>
          <template #footer>
            <vxe-button type="text" class="button-white" @click="cancelModelEvent">取消</vxe-button>
            <vxe-button type="text" class="button-blue" @click="confirmModelEvent">确定</vxe-button>
          </template>
        </vxe-modal>
      </Pane>
      <Pane size="30">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">模块设定</div>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :disabled="disabledTag" :loading="qloading" @click="findStaModelModuleList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="添加" :disabled="disabledTag" @click="addModuleDialog()"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="disabledTag" @click="staModelModuleDelete"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBox">
          <vxe-table ref="modelModuleTableRef" :data="modelModuleList" :loading="qloading" @current-change="modelModuleRowClick" class="mytable-scrollbar" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true}" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
            <vxe-column type="checkbox" width="30" align="center"></vxe-column>
            <vxe-column field="icon" title="图标" width="50">
              <template #default="{ row }">
                <el-icon size="20" class="icon">
                  <component :is="row.icon"></component>
                </el-icon>
              </template>
            </vxe-column>
            <vxe-column field="staModCode" title="标准编号" width="100">
            </vxe-column>
            <vxe-column field="modCode" title="模块编号" width="100">
            </vxe-column>
            <vxe-column field="modName" title="模块名称" width="140">
            </vxe-column>
            <vxe-column field="seq" title="顺序"> </vxe-column>
          </vxe-table>
        </div>
        <el-dialog title="模块字典" :show-close="false" v-model="showModuleDialog" append-to-body width="1000px" :close-on-click-modal="false" destroy-on-close v-if="showModuleDialog">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 130px" v-model="searchModuleForm.seachValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findStaModuleList2" @keyup="keyupModuleEnter" @search-click="findStaModuleList2()"></vxe-input>
              <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="findStaModuleList2"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody" style="height: 600px">
            <vxe-table ref="staModuleTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="staModuleList" :loading="lloading" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" :checkbox-config="{
                  checkMethod: checCheckboxkMethod2,
                  visibleMethod: showCheckboxkMethod2,
                  checkRowKeys: defaultSelecteRowKeys
                }" resizable show-overflow keep-source>

              <vxe-column type="checkbox" width="30px"></vxe-column>
              <vxe-column field="icon" title="图标" width="50">
                <template #default="{ row }">
                  <el-icon size="20" class="icon">
                    <component :is="row.icon"></component>
                  </el-icon>
                </template>
              </vxe-column>
              <vxe-column field="staModCode" title="标准编号" width="100">
              </vxe-column>
              <vxe-column field="modCode" title="模块编号" width="100">
              </vxe-column>
              <vxe-column field="modName" title="模块名称" width="100">
              </vxe-column>
              <vxe-column field="bigIcon" title="大图标" width="100">
              </vxe-column>
              <vxe-column field="phone" title="背景色" width="100">
                <template #default="{ row }">
                  <span class="margin-left-xs padding-lr-xs" :style="{ background: `${row.bigIconBgcolour}` }">{{ row.bigIconBgcolour }}</span>
                </template>
              </vxe-column>
              <vxe-column field="baseUrl" title="路径">
              </vxe-column>
              <vxe-column field="seq" title="顺序" width="50">
              </vxe-column>
            </vxe-table>

            <div class="dialog-footer flex right justify-end">
              <el-button type="primary" @click="saveBacthModule('staModuleTableRef')">确定</el-button>
              <el-button @click="closeModuleDialog('staModuleTableRef')">取消</el-button>
            </div>
          </div>
        </el-dialog>
      </Pane>
      <Pane size="50">
        <StaModelMenu ref="modelMenuRef" />
      </Pane>
    </Splitpanes>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import StaModelMenu from './StaModelMenu.vue';

defineExpose({ initPage });

let tloading = ref(false); //加载状态
let staModelList: any = reactive([]);
let sltStaModel: any = ref({});
let sltModelModule: any = ref({});
let isModelVisiable = ref(false);
let disabledTag = ref(true); //中间质控品维护按钮标记
let qloading = ref(false); //右侧质控表格加载+刷新
let modelModuleList: any = reactive([]); //右侧质控项目表格数据
let staModuleList: any = reactive([]);
let showModuleDialog = ref(false); //添加弹框展示状态
let lloading = ref(false); //弹框表格数据加载状态
let modelMenuRef: any = ref(null);

let searchModuleForm = reactive({
  seachValue: ''
});
let searchModelForm = {
  seachValue: ''
};

let staModelForm = reactive({
  id: null,
  modelCode: '',
  modelName: '',
  description: '',
  seq: 1,
  orgId: ''
});

let staModelFormRule = {
  modelName: [
    {
      required: true,
      message: '请输入模型名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ],
  modelCode: [
    {
      required: true,
      message: '请输入模型名称',
      trigger: 'blur'
    }
  ]
};

function initPage() {
  getStaModelList();
}

function getStaModelList() {
  tloading.value = true;
  staModelList.length = 0; //放入数据前清空数据
  const url = '/lis/sta/staModel/findStaModelList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchModelForm.seachValue
      }
    })
    .then((res: any) => {
      staModelList.push(...res.data);
      const kn = staModelList.find((k) => k.id == sltStaModel.value.id);
      if (isEmpty(kn)) {
        modelRowClick({ row: staModelList[0] }); //默认选中第一条数据
      } else {
        modelRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

// 点击设计模式表格当前行触发右侧表单变化
function modelRowClick({ row }: any) {
  if (isEmpty(row)) {
    clearStaModelForm();
    sltStaModel.value = {};
  } else {
    (proxy.$refs.staModelTableRef as any).setCurrentRow(row);
    sltStaModel.value = row;
    findStaModelModuleList();
  }
  if (!sltStaModel.value.id) {
    disabledTag.value = true;
  } else {
    //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
    disabledTag.value = false;
  }
}

function confirmModelEvent() {
  if (staModelForm.id === null) {
    const url = '/lis/sta/staModel/addStaModel';
    const staModel = {
      modelCode: staModelForm.modelCode,
      modelName: staModelForm.modelName,
      description: staModelForm.description,
      seq: staModelForm.seq
    };
    proxy.$http
      .post(url, staModel)
      .then((res: any) => {
        VxeMessage('新增成功', VxeNotifyType.success);
        clearStaModelForm();
        sltStaModel.value.id = res.data.id;
        getStaModelList();
        isModelVisiable.value = false;
      })
      .catch((err: any) => {
        VxeMessage('新增失败', VxeNotifyType.error);
      });
  } else {
    // 修改用户
    const url = '/lis/sta/staModel/editStaModel';

    const staModel = {
      id: staModelForm.id,
      modelCode: staModelForm.modelCode,
      modelName: staModelForm.modelName,
      description: staModelForm.description,
      seq: staModelForm.seq
    };
    proxy.$http
      .post(url, staModel)
      .then((res: any) => {
        VxeMessage('修改成功', VxeNotifyType.success);
        sltStaModel.value.id = res.data.id;
        clearStaModelForm();
        isModelVisiable.value = false;
        getStaModelList();
      })
      .catch((err: any) => {
        VxeMessage('修改失败', VxeNotifyType.error);
      });
  }
}

function deleteStaModel() {
  const sltStaModels = (proxy.$refs.staModelTableRef as any).getCheckboxRecords();
  if (!(sltStaModels.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delStaModelList = sltStaModels.filter((p: any) => !isEmpty(p.id));
        if (delStaModelList.length > 0) {
          const data = { staModelList: delStaModelList };
          const url = '/lis/sta/staModel/batchDeleteStaModelList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              getStaModelList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function findStaModelModuleList() {
  if (isEmpty(sltStaModel.value)) {
    VxeMessage('请选模型', VxeNotifyType.error);
  } else {
    qloading.value = true;
    modelModuleList.length = 0; //放入数据前清空数据
    const url = '/lis/sta/staModelModule/findStaModelModuleList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: { modelId: sltStaModel.value.id }
      })
      .then((res: any) => {
        modelModuleList.push(...res.data);
        const kn = modelModuleList.find((k) => k.id == sltModelModule.value.id);
        if (isEmpty(kn)) {
          modelModuleRowClick({ row: modelModuleList[0] }); //默认选中第一条数据
        } else {
          modelModuleRowClick({ row: kn }); //默认选中第一条数据
        }
        qloading.value = false;
      })
      .catch((err: any) => {
        qloading.value = false;
        VxeMessage('获取右侧获取质控项目表格数据异常', VxeNotifyType.error);
      });
  }
}

// 点击设计模式表格当前行触发右侧表单变化
function modelModuleRowClick({ row }: any) {
  if (isEmpty(row)) {
    sltModelModule.value = {};
    modelMenuRef.value.initPage(row);
  } else {
    (proxy.$refs.modelModuleTableRef as any).setCurrentRow(row);
    sltModelModule.value = row;
    modelMenuRef.value.initPage(row);
  }
}

// 添加按钮
function addModuleDialog() {
  if (isEmpty(sltStaModel.value)) {
    VxeMessage('请选择模型', VxeNotifyType.error);
  } else {
    findStaModuleList();
    showModuleDialog.value = true;
  }
}

function findStaModuleList() {
  lloading.value = true;
  staModuleList.length = 0; //放入数据前清空数据
  const url = '/lis/sta/staModule/findStaModuleList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchModuleForm.seachValue
      }
    })
    .then((res: any) => {
      staModuleList.push(...res.data);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
    });
}

function findStaModuleList2() {
  lloading.value = true;
  staModuleList.length = 0; //放入数据前清空数据
  const url = '/lis/sta/staModule/findStaModuleList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchModuleForm.seachValue
      }
    })
    .then((res: any) => {
      staModuleList.push(...res.data);
      const staModIds = modelModuleList.map((m) => m.staModId);
      const ilist = staModuleList.filter((p: any) => staModIds.includes(p.id));
      const $table = proxy.$refs.staModuleTableRef;
      $table.setCheckboxRow(ilist, true);
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
    });
}
// 回车查询
function keyupModuleEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findStaModuleList2();
  }
}

// 弹框取消按钮
function closeModuleDialog() {
  searchModuleForm.seachValue = '';
  showModuleDialog.value = false;
}

function saveBacthModule() {
  const selectRows = (proxy.$refs.staModuleTableRef as any).getCheckboxRecords();
  if (selectRows.length > 0) {
    const addModelModuleList = [];
    for (const sltRow of selectRows) {
      const modelModule = modelModuleList.find((qc: any) => qc.staModId == sltRow.id);
      if (isEmpty(modelModule)) {
        const addModelModule = {
          modelId: sltStaModel.value.id,
          modelCode: sltStaModel.value.modelCode,
          staModId: sltRow.id,
          staModCode: sltRow.staModCode,
          seq: sltRow.seq
        };
        addModelModuleList.push(addModelModule);
      }
    }
    if (addModelModuleList.length > 0) {
      const data = { staModelModuleList: addModelModuleList };
      const url = '/lis/sta/staModelModule/batchAddStaModelModuleList';
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          findStaModelModuleList(); // 获取检验仪器表格数据
          VxeMessage(res.status.msg, VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage(err, VxeNotifyType.error);
        });
    } else {
      VxeMessage('请选择要添加的数据', VxeNotifyType.error);
    }
  }
  closeModuleDialog();
}

function staModelModuleDelete() {
  const sltModelModules = (proxy.$refs.modelModuleTableRef as any).getCheckboxRecords();
  if (!(sltModelModules.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { staModelModuleList: sltModelModules };
        const url = '/lis/sta/staModelModule/batchDeleteStaModelModuleList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findStaModelModuleList(); // 获取检验仪器表格数据
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 编辑当前行规则
function setStaModelForm(row: any) {
  staModelForm.id = row.id;
  staModelForm.modelCode = row.modelCode;
  staModelForm.modelName = row.modelName;
  staModelForm.seq = row.seq;
  staModelForm.orgId = row.orgId;
  staModelForm.description = row.description;
  //   const temp: any = proxy.$refs['refCkEditor'];
  //   if (isEmpty(staModelForm.description)) {
  //     temp.setValue('');
  //   } else {
  //     temp.setValue(staModelForm.description);
  //   }
}
// 清空中间规则弹框表单
function clearStaModelForm() {
  staModelForm.id = null;
  staModelForm.modelCode = '';
  staModelForm.modelName = '';
  staModelForm.description = '';
  staModelForm.seq = 1;
  staModelForm.orgId = '';
  //   const temp: any = proxy.$refs['refCkEditor'];
  //   temp.setValue('');
}

function editStaModelDialog(row: any) {
  setStaModelForm(row);
  isModelVisiable.value = true;
}

function addStaModelDialog() {
  isModelVisiable.value = true;
}

function cancelModelEvent() {
  clearStaModelForm();
  isModelVisiable.value = false;
}

// 回车查询
function keyupModelEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getStaModelList();
  }
}

let defaultSelecteRowKeys = reactive([]);
// 弹框 表格复选框(是否允许用户手动勾选)
function checCheckboxkMethod2({ row }: any) {
  defaultSelecteRowKeys.length = 0;
  const obj = modelModuleList.filter((p: any) => {
    defaultSelecteRowKeys.push(p.staModId);
    return p.staModId == row.id;
  });
  return obj.length == 0;
}

// 弹框 表格复选框 设置(是否显示复选框)
function showCheckboxkMethod2({ row }: any) {
  const obj = modelModuleList.filter((p: any) => {});
  return obj.length == 0;
}
</script>

<style lang="scss" scoped>
#staModelSeDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .modelTable {
    height: calc(100% - 40px);
    background-color: $base-white;
  }

  .tableBox {
    height: calc(100% - 40px);
  }
}
</style>